package com.jmlong.controller;

import com.jmlong.domain.Address;
import com.jmlong.domain.User;
import com.jmlong.service.UserService;
import com.jmlong.utils.JwtUtil;
import com.jmlong.utils.Result;
import javafx.geometry.Pos;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
//@CrossOrigin(origins = "http://localhost:8080") 允许跨域
public class UserController {

    @Autowired
    UserService userService;


    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(ServletResponse servletResponse,@RequestBody Map params) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String loginName = (String) params.get("loginName");
        String password = (String) params.get("password");

        log.info(loginName+"用户登陆");

        if (password!=null&&!password.equals("")){
            password = MD5(password);
        }

        User user = userService.login(loginName, password);
        Result result = new Result();
        if( user != null ){

            if (user.getStatus().equals("0")){
                result.setCode(400);
                result.setMsg("您的账号已注销！禁止登陆！");
                return result;
            }

            log.info("用户登录成功！生成token！");
            String token = JwtUtil.createToken(user);
            response.setHeader("Access-Control-Expose-Headers","Authorization");
            response.setHeader("Authorization",token);
            result.setCode(200);
            result.setMsg("登录成功!");

            HashMap<String,String> map = new HashMap<>();
            map.put("nickname",user.getName());
            map.put("phoneNum",user.getPhone());
            map.put("img",user.getImg());
            map.put("identityCode",user.getIdentity());
            result.setData(map);
            return result;

        }else{
            log.info("用户帐号密码出错！");
            result.setCode(400);
            result.setMsg("您的帐号密码输入错误！");
            return result;
        }


    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result register(ServletResponse servletResponse,@RequestBody Map params){
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Result result = new Result();
        String nickname = (String) params.get("nickname");
        String loginName = (String) params.get("loginName");
        String password = (String) params.get("password");
        String phoneNum = (String) params.get("phoneNum");
        String identity = (String) params.get("identity");

        password = MD5(password);

        log.info(nickname+"/"+loginName+"/"+password+"/"+phoneNum);


        User login = userService.repeat(loginName);

        if (login!=null){
            result.setMsg("该账号已被注册，请重新注册！");
            result.setCode(500);
            return result;
        }

        log.info("新用户注册");
        Result res  = userService.register(nickname, loginName, password,phoneNum,identity);
        if(res.getCode()==200){
            log.info("新用户注册成功");
            User user = new User();
            user.setLoginName(loginName);
            user.setName(nickname);
            String token = JwtUtil.createToken(user);
            response.setHeader("Access-Control-Expose-Headers","Authorization");
            response.setHeader("Authorization",token);
            res.setMsg("注册成功!");
            return res;
        }else{
            log.info("新用户注册失败");
            result.setCode(400);
            result.setMsg("注册失败!");
            return result;
        }

    }

    /**
     * 获取用户所有信息
     */
    @PostMapping ("/getUserInfo")
    public Result userInfo(ServletRequest servletRequest){
        Result result = new Result();
        String loginName = (String) servletRequest.getAttribute("loginName");
        String nickname = (String) servletRequest.getAttribute("name");

        User userInfo = userService.getUserInfo(loginName, nickname);
        userInfo.setPassWord("null");

        if (userInfo!=null){
            result.setCode(200);
            result.setMsg("获取用户信息成功");
            result.setData(userInfo);

        }else{
            result.setCode(500);
            result.setMsg("获取用户信息失败");

        }
        return result;
    }

    /**
     * 用户上传头像
     * @param file      文件流
     */

    @PostMapping("/uploadProfilePicture")
    public Result uploadProfilePicture(ServletRequest servletRequest,MultipartFile file){

        Result result = new Result();
        String loginName = (String) servletRequest.getAttribute("loginName");
        String nickname = (String) servletRequest.getAttribute("name");

        User userInfo = userService.getAll(loginName);
        if (userInfo==null){
            result.setCode(500);
            result.setMsg("该用户信息不存在");
            return result;
        }


        String path = "D:\\GraduationJava\\src\\main\\resources\\static\\assest\\img\\userImg";

        String fileName = file.getOriginalFilename();//获取上传的文件名称
        int suffixTemp = fileName.lastIndexOf(".");
        String suffixName = "";
        if (suffixTemp!= -1){
            suffixName=fileName.substring(suffixTemp);//获取文件后缀
            if(!suffixName.equals(".jpg")){
                if (!suffixName.equals(".jpeg")){
                    if (!suffixName.equals(".png")){
                        result.setCode(400);
                        result.setMsg("用户上传文件非法!");
                        return result;
                    }
                }
            }
        }else{
            result.setCode(400);
            result.setMsg("用户上传文件异常!");
            return result;
        }
        Date date = new Date();
        long dateStr = date.getTime();
        fileName = loginName +dateStr+ suffixName; //重新命名上传的图片名称

        File targetFile = new File(path);
        File saveFile = new File(targetFile, fileName);
        try {
            file.transferTo(saveFile);
            log.info("用户头像保存成功....");
        }catch (Exception e){
            log.error("用户上传头像失败....",e);
            result.setCode(500);
            result.setMsg("头像上传失败,请稍候再试");
            return result;
        }
        User user = new User();
        String img = "/img/userImg/"+fileName;
        user.setName(nickname);
        user.setLoginName(loginName);
        user.setImg(img);

        Integer res = userService.uploadProfilePicture(user);//更新用户头像到数据库

        if (res==1){

            String oldFileName = userInfo.getImg();
            if (!oldFileName.contains("defaultHeader.png")){        //判断是否为默认头像资源，如果不是，则删除旧得图片资源
                oldFileName = oldFileName.substring(oldFileName.lastIndexOf("/")+1);
                File oldFile = new File(targetFile,oldFileName);
                boolean delete = oldFile.delete();
                if (delete){
                    log.info("用户旧头像资源删除成功！");
                }else{
                    log.error("用户旧头像资源删除失败吧  ！");
                }
            }

            HashMap<String,String> map = new HashMap<>();
            map.put("img","/img/userImg/"+fileName);
            result.setCode(200);
            result.setData(map);
            result.setMsg("上传头像成功！");
            log.info("用户更改头像成功");
        }else {
            result.setCode(500);
            result.setMsg("上传头像失败！");
            boolean delete = saveFile.delete();
            if (delete){
                log.info("用户头像同步数据库出错...");
                log.info("图片已删除");
            }else{
                log.info("用户图像删除失败");
            }
        }
        return result;
    }

    /**
     * 用户添加地址
     */
    @PostMapping("/addAddress")
    public Result addAddress(ServletRequest servletRequest,@RequestBody Map params){
        log.info("用户添加地址信息中...");
        Result result = new Result();
        String loginName = (String) servletRequest.getAttribute("loginName");
        Integer res = userService.addAddress(loginName, params);
        if (res!=0){
            log.info("用户添加地址信息成功！");
            result.setMsg("用户添加地址成功！");
        }else{
            log.info("用户添加地址信息失败！");
            result.setCode(500);
            result.setMsg("用户添加地址失败！");
        }

        return result;
    }

    /**
     * 用户更新地址信息
     */
    @PostMapping("/updateAddress")
    public Result updateAddress(@RequestBody Map params){
        log.info("用户更新地址信息中.....");
        Result result = new Result();

        Integer res = userService.updateAddress(params);
        if (res!=0){
            log.info("用户更新地址信息成功！");
            result.setMsg("更新地址信息成功！");
        }else{
            log.info("用户更新地址信息失败！");
            result.setCode(500);
            result.setMsg("更新地址信息错误！");
        }

        return result;
    }

    /**
     * 用户删除地址信息
     */
    @PostMapping ("/delAddressInfo")
    public Result delAddressInfo(@RequestBody Map params){
        log.info("用户请求删除地址信息....");
        Result result = new Result();
        Integer res = userService.delAddressInfo(params);
        if (res!=0){
            log.info("用户请求删除地址成功！");
            result.setMsg("用户删除信息地址成功！");
        }else{
            log.info("用户地址信息删除失败！");
            result.setCode(500);
            result.setMsg("用户地址信息删除失败！");
        }
        return  result;
    }


    /**
     * 用户请求地址信息
     */
    @GetMapping("/getAddressInfo")
    public Result getAddressInfo(ServletRequest servletRequest){
        log.info("用户请求地址信息...");
        Result result = new Result();
        String loginName = (String) servletRequest.getAttribute("loginName");
        List<Address> list = userService.getAddressInfo(loginName);
        if (list!=null){
            log.info("用户地址信息请求成功！");
            result.setMsg("用户地址信息查询成功！");
            result.setData(list);
        }else if (list.size()==0){
            log.info("用户地址信息请求成功！暂无用户地址信息！");
            result.setCode(400);
            result.setMsg("暂无用户地址信息！");
        }else {
            log.info("用户地址信息请求失败！");
            result.setCode(500);
            result.setMsg("查询用户地址信息失败");
        }
        return  result;
    }



    /**
     *  商户注销接口
     * @param servletRequest 服务器请求信息
     * @return
     */

    @GetMapping("/removal")
    public Result userRemoval(ServletRequest servletRequest){
        log.info("用户账户注销中....");
        String nickName = (String) servletRequest.getAttribute("name");
        String loginName = (String) servletRequest.getAttribute("loginName");

        Integer res = userService.userRemoval(nickName, loginName);
        Result result = new Result();
        if (res!=0){
            log.info("用户注销成功");
            result.setCode(200);
            result.setMsg("注销成功！");
        }else{
            log.error("用户注销失败");
            result.setCode(500);
            result.setMsg("注销失败！");
        }
        return result;
    }

    /**
     *  更新用户信息
     * @param params
     */
    @PostMapping("/updateInfo")
    public Result updateInfo(ServletRequest servletRequest,ServletResponse servletResponse,@RequestBody Map params){
        log.info("用户更新个人信息中...");
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Result result = new Result();
        String loginName = (String) servletRequest.getAttribute("loginName");

        String name = (String) params.get("nickname");
        String phone = (String) params.get("phoneNum:");
        String oldPass = (String) params.get("oldPass");
        String newPass = (String) params.get("newPass");

        Integer res = null;
        if (oldPass==null||oldPass.equals("")){
            res = userService.updateInfo(loginName, name, "", phone);
        }else{
            oldPass = MD5(oldPass);
            User login = userService.login(loginName, oldPass);
            if (login!=null){
                newPass = MD5(newPass);
                res = userService.updateInfo(loginName,name,newPass,phone);
            }else{
                log.info("用户更新密码失败！");
                log.info("更新个人信息失败！");
                result.setCode(400);
                result.setMsg("您的原始密码输入错误！");
                return  result;
            }
        }

        if (res==1){
            if (name!=null || !name.equals("")){
                User user = new User();
                User info = userService.getAll(loginName);
                user.setLoginName(loginName);
                user.setName(info.getName());
                String token = JwtUtil.createToken(user);
                response.setHeader("Access-Control-Expose-Headers","Authorization");
                response.setHeader("Authorization",token);
            }
            log.info("更新个人信息成功！");
            result.setMsg("个人信息更新成功！");
        }else{
            log.info("更新个人信息失败！");
            result.setCode(500);
            result.setMsg("个人信息更新失败");
        }

        return result;

    }


    /**
     * 字符串MD5加密
     * @params 原始字符串
     * @return  加密后字符串
     */
    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' };
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
